﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using InnovTech.Persistence;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace NHibernate.Util
{
    public abstract class NHibernateDatabaseGeneratorBase<TDatabaseInfo> : DatabaseGeneratorBase<TDatabaseInfo>
        where TDatabaseInfo : IDatabaseInfo
    {

        protected TDatabaseInfo _info;
        public void SetDatabaseInfo(TDatabaseInfo info)
        {
            _info = info;
        }

        public abstract Configuration GetConfiguration(TDatabaseInfo info);
        protected abstract void CreateEmptyDatabase(TDatabaseInfo info);

        protected override void CreateDatabase(TDatabaseInfo info)
        {
            CreateEmptyDatabase(info);
            Configuration config = GetConfiguration(info);
            ImportDatabaseSchema(config);
        }

        protected void ImportDatabaseSchema(Configuration config)
        {
            SchemaExport export = new SchemaExport(config);
            export.Create(false, true);
        }

        public string GenerateSqlScript()
        {
            Configuration config = GetConfiguration(GetDatabaseInfo());
            SchemaExport exporter = new SchemaExport(config);
            string tmpPath = Directory.GetCurrentDirectory() + "\\" + Guid.NewGuid().ToString() + ".sql";
            exporter.SetOutputFile(tmpPath);
            exporter.Create(true, false);

            string result = null;
            if (File.Exists(tmpPath))
            {
                using (FileStream stream = File.OpenRead(tmpPath))
                using (StreamReader reader = new StreamReader(stream))
                {
                    result = reader.ReadToEnd();
                    reader.Close();
                    stream.Close();
                }

                File.Delete(tmpPath);
            }
            return result;
        }
        
    }
}
